package com.zhiyou100.controller;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zhiyou100.model.User;
import com.zhiyou100.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {
	
	@Resource
	private UserService userService;
	
	@RequestMapping("loginOut.do")
	public String loginOut(){
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		return"forward:/login.jsp";
	}
	
	@RequiresPermissions(value="user:update")
	@RequestMapping("update.do")
	public String update(User user){
		userService.update(user);
		return"redirect:show.do";
	}
	
	@RequiresPermissions(value="user:update")
	@RequestMapping("edit.do")
	public String edit(Model model,int id){
		model.addAttribute("user",userService.queryById(id));
		return"user/edit";
	}
	
	@RequiresPermissions(value="user:delete")
	@RequestMapping("delete.do")
	public String delete(int id){
		userService.deleteById(id);
		return"redirect:show.do";
	}
	
	@RequiresPermissions(value="user:insert")
	@RequestMapping("insert.do")
	public String insert(User user){
		userService.add(user);
		return"redirect:show.do";
	}
	
	@RequiresPermissions(value="user:insert")
	@RequestMapping("add.do")
	public String add(){
		
		return"user/add";
	}
	
//	@RequiresRoles(value={"程序员","老师"},logical=Logical.OR)
	@RequestMapping("show.do")
	@RequiresPermissions(value = "user:select")
	public String show(Model model) {
		model.addAttribute("users", userService.queryAll());
		return "user/show";
	}
//	要将当前的请求设置为anon
	@RequestMapping("login.do")
	public String login(User user,Model model){
		try {
			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(),user.getPassword());
			subject.login(token);
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "登录失败");
			return "forward:/login.jsp";
		}
		
		return "redirect:show.do";
	}
}
